package com.ambow.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.naming.InsufficientResourcesException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.sql.Select;

import com.ambow.dao.ManagerDao;
import com.ambow.dao.impl.ManagerDaoImpl;
import com.ambow.entity.Message;
import com.ambow.entity.News;
import com.ambow.entity.Product;
import com.ambow.entity.User;
import com.ambow.service.ManagerService;
import com.ambow.service.MessageService;
import com.ambow.service.NewsService;
import com.ambow.service.ProductService;
import com.ambow.service.UserService;
import com.ambow.service.impl.ManagerServiceImpl;
import com.ambow.service.impl.MessageServiceImpl;
import com.ambow.service.impl.NewsServiceImpl;
import com.ambow.service.impl.ProductServiceImpl;
import com.ambow.service.impl.UserServiceImpl;
import com.ambow.utils.PageResults;

/**
 * Servlet implementation class ManagerServlet
 */
@WebServlet("/ManagerServlet")
public class ManagerServlet extends HttpServlet {

	Integer pageSize = 8;//每页显示的条数
	ManagerService ms = new ManagerServiceImpl();
	UserService userService = new UserServiceImpl();
	ProductService productService = new ProductServiceImpl();
	MessageService messageService = new MessageServiceImpl();
	NewsService newsService = new NewsServiceImpl();
	SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String status = request.getParameter("status");
		if (status.equals("user")) {
			queryUser(request, response,status);// 查询全部用户
		} else if (status.equals("deleteUser")) {
			deleteUser(request, response,status);// 删除用户（修改状态）
		} else if (status.equals("product")) {
			queryProduct(request, response,status);// 查询全部商品
		} else if (status.equals("deleteProduct")) {
			deleteProduct(request, response,status);// 删除商品（修改状态）
		} else if (status.equals("modifyProduct")) {
			modifyProduct(request, response,status);// 修改商品信息
		} else if (status.equals("select")) {
			selectProduct(request, response,status);// 根据条件查询商品
		} else if (status.equals("addProduct")) {
			addProduct(request, response,status);// 添加商品
		} else if (status.equals("news")) {
			queryNews(request, response,status);// 查询全部新闻
		} else if (status.equals("addNews")) {
			addNews(request, response,status);// 添加新闻
		} else if (status.equals("updateStatus")) {
			updateNews(request, response,status);// 修改新闻的状态
		} else if (status.equals("message")) {
			queryMessage(request, response,status);// 查询全部留言
		} else if(status.equals("updateMessageStatus")){
			updataMessageStatus(request, response,status);//删除留言（即修改状态）
		}
	}

	// 查询全部留言
	public void queryMessage(HttpServletRequest request, HttpServletResponse response,String status) {
		try {
			String hql = "from Message where status=1";//查询全部
			String countHql = "select count(*) from Message";//总的记录数
			Integer pageNo = Integer.valueOf(request.getParameter("currentPage"));// 当前页
			PageResults<Message> pageResults = messageService.getPageByFetchedHql(hql, countHql, pageNo, pageSize);
			System.out.println(pageResults.getTotalCount() + "yuyuyuyuyuyuyuyu");
			if (pageResults != null) {
				request.setAttribute("pageResults", pageResults);
				request.setAttribute("status", status);
				request.getRequestDispatcher("pages/message_result.jsp").forward(request, response);
			}else {
				System.out.println("查询失败，数据库中没有数据");
			}
		} catch (Exception e) {
		}

	}

	// 查询全部新闻
	public void queryNews(HttpServletRequest request, HttpServletResponse response,String status) {
		try {
			String hql = "from News where status=1 order by publishTime desc";//查询全部
			String countHql = "select count(*) from News where status=1 order by publishTime desc";//总的记录数
			Integer pageNo = Integer.valueOf(request.getParameter("currentPage"));// 当前页
			PageResults<News> pageResults = newsService.getPageByFetchedHql(hql, countHql, pageNo, pageSize);
			System.out.println(pageResults.getTotalCount() + "yuyuyuyuyuyuyuyu");
			if (pageResults != null) {
				request.setAttribute("pageResults", pageResults);
				request.setAttribute("status", status);
				request.getRequestDispatcher("pages/news_result.jsp").forward(request, response);
			}else {
				System.out.println("查询失败，数据库中没有数据");
			}
		} catch (Exception e) {
		}
	}

	// 添加商品
	public void addProduct(HttpServletRequest request, HttpServletResponse response,String status) {
		try {
			String name = request.getParameter("name");
			String number = request.getParameter("number");
			String color = request.getParameter("color");
			String kind = request.getParameter("kind");
			String brand = request.getParameter("brand");
			String label = request.getParameter("label");
			String size = request.getParameter("size");
			String type = request.getParameter("type");
			String photo = request.getParameter("photo");
			int amount = Integer.parseInt(request.getParameter("amount"));
			double price = Double.parseDouble(request.getParameter("price"));
			Product product = new Product();
			product.setAmount(amount);
			product.setBrand(brand);
			product.setColor(color);
			product.setKind(kind);
			product.setLabel(label);
			product.setName(name);
			product.setPrice(price);
			product.setStatus(1);
			product.setPhoto(photo);
			product.setNumber(number);
			product.setPublishTime(date.parse(request.getParameter("publishTime")));
			product.setSize(size);
			product.setType(type);
			boolean f = ms.addProduct(product);
			if (f) {
				String hql = "from Product";//查询全部
				String countHql = "select count(*) from Product";//总的记录数
				Integer pageNo = 0;// 当前页
				PageResults<Product> pageResults = productService.getPageByFetchedHql(hql, countHql, pageNo, pageSize);
				System.out.println(pageResults.getTotalCount() + "yuyuyuyuyuyuyuyu");
				if (pageResults != null) {
					status="product";
					request.setAttribute("pageResults", pageResults);
					request.setAttribute("status", status);
					request.getRequestDispatcher("pages/product_result.jsp").forward(request, response);
				}else {
					System.out.println("查询失败，数据库中没有数据");
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 根据编号/款式/颜色/类型进行查询
	public void selectProduct(HttpServletRequest request, HttpServletResponse response,String status) {
		try {
			String xuanze = request.getParameter("xuanze");// 根据什么进行查询
			String find = request.getParameter("find");// 查询条件的值
			String hql = null;
			String countHql = null;
			if (xuanze.equals("编号")) {
				hql = "from Product where number='"+find+"'";
				countHql = "select count(*) from Product where number='"+find+"'";
			} else if (xuanze.equals("款式")) {
				hql = "from Product where label='"+find+"'";
				countHql = "select count(*) from Product where label='"+find+"'";
			} else if (xuanze.equals("颜色")) {
				hql = "from Product where color='"+find+"'";
				countHql = "select count(*) from Product where color='"+find+"'";
			} else if (xuanze.equals("类型")) {
				hql = "from Product where kind='"+find+"'";
				countHql = "select count(*) from Product where kind='"+find+"'";
			}
			Integer pageNo = Integer.valueOf(request.getParameter("currentPage"));// 当前页
			PageResults<Product> pageResults = productService.getPageByFetchedHql(hql, countHql, pageNo, pageSize);
			System.out.println(pageResults.getTotalCount() + "yuyuyuyuyuyuyuyu");
			if (pageResults != null) {
				request.setAttribute("pageResults", pageResults);
				request.setAttribute("status", status);
				request.getRequestDispatcher("pages/product_result.jsp").forward(request, response);
			}else {
				System.out.println("查询失败，数据库中没有数据");
				response.sendRedirect("pages/product_result.jsp");
			}
		} catch (Exception e) {
		}
	}

	// 修改商品信息
	public void modifyProduct(HttpServletRequest request, HttpServletResponse response,String status) {
		try {
			int id = Integer.parseInt(request.getParameter("id"));// 被修改商品的id
			String name = request.getParameter("name");// 商品名
			String color = request.getParameter("color");// 商品颜色
			String kind = request.getParameter("kind");// 类别
			String brand = request.getParameter("brand");// 品牌
			String label = request.getParameter("label");// 标签（流行。。。）
			String size = request.getParameter("size");// 尺寸
			int amountt = Integer.parseInt(request.getParameter("amount"));// 库存数量
			double pricee = Double.parseDouble(request.getParameter("price"));// 价格
			Product product = ms.queryOneProduct(id);
			product.setName(name);
			product.setAmount(amountt);
			product.setBrand(brand);
			product.setColor(color);
			product.setPrice(pricee);
			product.setKind(kind);
			product.setSize(size);
			product.setLabel(label);
			boolean f1 = ms.delete_modifyProduct(product);
			if (f1) {
				String hql = "from Product";
				String countHql = "select count(*) from Product";//总的记录数
				Integer pageNo = 0;// 当前页
				PageResults<Product> pageResults = productService.getPageByFetchedHql(hql, countHql, pageNo, pageSize);
				System.out.println(pageResults.getTotalCount() + "yuyuyuyuyuyuyuyu");
				if (pageResults != null) {
					request.setAttribute("pageResults", pageResults);
					request.setAttribute("status", status);
					request.getRequestDispatcher("pages/product_result.jsp").forward(request, response);
				}else {
					System.out.println("查询失败，数据库中没有数据");
					response.sendRedirect("pages/product_result.jsp");
				}
			}
		} catch (Exception e) {
		}

	}

	// 删除商品(实则修改状态，使其下架)
    public void deleteProduct(HttpServletRequest request, HttpServletResponse response,String status) {
		try {
			int id = Integer.parseInt(request.getParameter("id"));// 被删除商品的id
			Product product = ms.queryOneProduct(id);
			product.setStatus(0);
			boolean f = ms.delete_modifyProduct(product);
			if (f) {
				String hql = "from Product";
				String countHql = "select count(*) from Product";//总的记录数
				Integer pageNo = 0;// 当前页
				PageResults<Product> pageResults = productService.getPageByFetchedHql(hql, countHql, pageNo, pageSize);
				System.out.println(pageResults.getTotalCount() + "yuyuyuyuyuyuyuyu");
				if (pageResults != null) {
					request.setAttribute("pageResults", pageResults);
					request.setAttribute("status", status);
					request.getRequestDispatcher("pages/product_result.jsp").forward(request, response);
				}else {
					System.out.println("查询失败，数据库中没有数据");
					response.sendRedirect("pages/product_result.jsp");
				}
			}
		} catch (Exception e) {
		}
	}

	// 查询全部商品
	public void queryProduct(HttpServletRequest request, HttpServletResponse response,String status) {
		try {
			String hql = "from Product";//查询全部
			String countHql = "select count(*) from Product";//总的记录数
			Integer pageNo = Integer.valueOf(request.getParameter("currentPage"));// 当前页
			PageResults<Product> pageResults = productService.getPageByFetchedHql(hql, countHql, pageNo, pageSize);
			System.out.println(pageResults.getTotalCount() + "yuyuyuyuyuyuyuyu");
			if (pageResults != null) {
				request.setAttribute("pageResults", pageResults);
				request.setAttribute("status", status);
				request.getRequestDispatcher("pages/product_result.jsp").forward(request, response);
			}else {
				System.out.println("查询失败，数据库中没有数据");
			}
		} catch (Exception e) {
		}

	}

	// 删除用户(并非真正意义上的删除，实则将其状态修改，使之成黑名单)
	public void deleteUser(HttpServletRequest request, HttpServletResponse response,String status) {
		try {
			int id = Integer.parseInt(request.getParameter("id"));// 被删除用户的id
			User user = ms.queryOneUser(id);// 根据id查到该用户
			user.setStatus(0);// 将其状态修改
			boolean f = ms.delete_modifyUser(user);
			if (f) {
				String hql = "from User";
				String countHql = "select count(*) from User";
				Integer pageNo = 0;
				PageResults<User> pageResults = ms.getPageByFetchedHql(hql, countHql, pageNo, pageSize);
				request.setAttribute("pageResults", pageResults);
				request.setAttribute("status", status);
				request.getRequestDispatcher("pages/user_result.jsp").forward(request, response);
			} else {
				System.out.println("删除失败!不能进行修改");
			}
		} catch (Exception e) {
		}

	}

	// 查询全部用户
	public void queryUser(HttpServletRequest request, HttpServletResponse response,String status) {
		try {
			String hql = "from User";// 查询全部数据
			String countHql = "select count(*) from User";// 计算总的记录数
			Integer pageNo = Integer.valueOf(request.getParameter("currentPage"));// 当前页
			PageResults<User> pageResults = userService.getPageByFetchedHql(hql, countHql, pageNo, pageSize);
			System.out.println(pageResults.getTotalCount() + "yuyuyuyuyuyuyuyu");
			if (pageResults != null) {
				request.setAttribute("pageResults", pageResults);
				request.setAttribute("status", status);
				request.getRequestDispatcher("pages/user_result.jsp").forward(request, response);
			}
		} catch (Exception e) {
		}

	}

	//修改新闻（实则修改状态）
	public void updateNews(HttpServletRequest request, HttpServletResponse response,String status) {
		try {
			ManagerService managerService = new ManagerServiceImpl();
			Integer id = Integer.valueOf(request.getParameter("id"));
			News news = managerService.queryOneNews(id);
			news.setStatus(0);
			boolean b = managerService.updateStatus(news);
			if (b) {
				String hql = "from News";
				String countHql = "select count(*) from News";
				Integer pageNo = 0;
				PageResults<News> pageResults = newsService.getPageByFetchedHql(hql, countHql, pageNo, pageSize);
				request.setAttribute("pageResults", pageResults);
				request.setAttribute("status", status);
				request.getRequestDispatcher("pages/news_result.jsp").forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//添加新闻
	public void addNews(HttpServletRequest request, HttpServletResponse response,String status) {
		ManagerService managerService = new ManagerServiceImpl();
		try {
			String title = request.getParameter("title");
			String content = request.getParameter("content");
			Date publishTime = date.parse(request.getParameter("publishTime"));
			Integer Status = Integer.valueOf(request.getParameter("Status"));
			News news = new News();
			news.setTitle(title);
			news.setContent(content);
			news.setPublishTime(publishTime);
			news.setStatus(Status);
			boolean b = managerService.addNews(news);
			if (b) {
				String hql = "from News";
				String countHql = "select count(*) from News";
				Integer pageNo = 0;
				PageResults<News> pageResults = newsService.getPageByFetchedHql(hql, countHql, pageNo, pageSize);
				request.setAttribute("pageResults", pageResults);
				status = "news";
				request.setAttribute("status", status);
				request.getRequestDispatcher("pages/news_result.jsp").forward(request, response);
			} else {
				System.out.println("添加失败");
				response.sendRedirect("pages/news_add.jsp");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 

	}

	//修改留言（即修改状态）
	public void updataMessageStatus(HttpServletRequest request, HttpServletResponse response,String status) {
		// TODO Auto-generated method stub
		try {
			ManagerService mService = new ManagerServiceImpl();
			Integer id = Integer.valueOf(request.getParameter("id"));
			Message ms = mService.queryOneMessage(id);
			ms.setStatus(0);
			boolean b = mService.updateMessageStatus(ms);
			if (b) {
				String hql = "from Message";
				String countHql = "select count(*) from Message";
				Integer pageNo = 0;
				PageResults<News> pageResults = newsService.getPageByFetchedHql(hql, countHql, pageNo, pageSize);
				request.setAttribute("pageResults", pageResults);
				request.setAttribute("status", status);
				request.getRequestDispatcher("pages/message_result.jsp").forward(request, response);
			}
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
